package
{
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.text.*;
	import flash.utils.Timer;
	import flash.utils.getTimer;
	
	
	/** Create a clock that counts down by the second to 0 then dispatches an Event Complete event */ 
	public class CountdownClock extends MovieClip
	{
		public var WIDTH:Number, HEIGHT:Number;
		public var OUTLINE_COLOR:uint, FILL_COLOR:uint, TEXT_COLOR:uint;
		private var total_msecs:uint, current_msecs:uint;
		private var ellipseMultiplier:Number;
		private var tfield:TextField;
		private var timer:Timer;
		
		public function CountdownClock(WIDTH:Number, HEIGHT:Number, msecs:uint, ellipseMultiplier:Number=0, OUTLINE_COLOR:uint=0x888888, FILL_COLOR:uint=0x222222, TEXT_COLOR:uint=0xFFFFFF)
		{
			this.WIDTH = WIDTH;
			this.HEIGHT = HEIGHT;
			this.total_msecs = msecs;
			this.current_msecs = msecs;
			this.ellipseMultiplier = ellipseMultiplier;
			this.OUTLINE_COLOR = OUTLINE_COLOR;
			this.FILL_COLOR = FILL_COLOR;
			this.TEXT_COLOR = TEXT_COLOR;
			this.graphics.lineStyle(WIDTH/20, OUTLINE_COLOR);
			this.graphics.beginFill(FILL_COLOR);
			this.graphics.drawRoundRect(0, 0, WIDTH, HEIGHT, WIDTH*ellipseMultiplier, HEIGHT*ellipseMultiplier);
			this.graphics.endFill();
			tfield = new TextField();
			tfield.defaultTextFormat = new TextFormat("Arial", this.HEIGHT*3/4, TEXT_COLOR);
			tfield.text = String(calcMinutesString(current_msecs)+":"+calcSecondsString(current_msecs));
			tfield.autoSize = "right";
			tfield.x = (this.WIDTH - tfield.width)/2;
			tfield.y = (this.HEIGHT - tfield.height)/2;
			this.addChild(tfield);
			
			// setup timer
			timer = new Timer(1000, total_msecs/1000);
		}
		
		public function start():void
		{
			timer.addEventListener(TimerEvent.TIMER, handleTimerSecond);
			timer.addEventListener(TimerEvent.TIMER_COMPLETE, handleTimerComplete);
			timer.start();
		}
		private function handleTimerSecond (event:TimerEvent):void
		{
			current_msecs-=1000;
			tfield.text = String(calcMinutesString(current_msecs)+":"+calcSecondsString(current_msecs));
		}
		private function handleTimerComplete (event:Event):void
		{
			timer.removeEventListener(TimerEvent.TIMER, handleTimerSecond);
			timer.removeEventListener(TimerEvent.TIMER_COMPLETE, handleTimerComplete);
			timer.stop();
			this.dispatchEvent( new Event(Event.COMPLETE ));
		}
		
		private static function calcMinutesString(msecs:uint):String
		{
			var mins:uint = Math.floor((msecs/1000)/60);
			if (mins < 10)
			{
				return String(" "+mins);
			} else
			{
				return String(mins);
			}
		}
		private static function calcSecondsString(msecs:uint):String
		{
			var secs:uint = (msecs/1000)%60;
			if (secs < 10)
			{
				return String("0"+secs);
			} else
			{
				return String(secs);
			}
		}	
	}
}